import React, { useEffect } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import { Result, Button } from 'antd-mobile'
import TopNavbar from '../../components/TopNavbar'
import styles from './index.module.css'
import { addBill } from '../../services/paymentService'
import { addLocalRecord } from '../../services/recordsService'

const RegisterResult = () => {
  const { state } = useLocation()
  const navigate = useNavigate()
  const success = state?.success
  const bookingId = state?.bookingId
  const payAmount = state?.payAmount
  const doctor = state?.doctor
  const slot = state?.slot

  useEffect(() => {
    if (!success) return
    const bill = {
      id: bookingId,
      billNo: bookingId,
      patientName: '王小柯',
      department: doctor?.deptName || '门诊科室',
      doctorName: doctor?.name || '值班医生',
      billDate: new Date().toISOString().slice(0, 10),
      billType: '门诊挂号费',
      amount: Number(payAmount || doctor?.fee || 0),
      status: '待缴费',
      timeRange: slot?.time
    }
    addBill(bill)
    addLocalRecord({
      id: bookingId,
      date: `${new Date().toISOString().slice(0, 10)} ${slot?.time?.split(' ')[1] || ''}`.trim(),
      type: '挂号',
      dept: doctor?.deptName || '门诊科室',
      doctor: `${doctor?.name || '值班医生'}（${doctor?.title || '执业医师'}）`,
      hospital: '四川省保健院南苑'
    })
  }, [success, bookingId, payAmount, doctor, slot])

  return (
    <div className={styles.page}>
      <TopNavbar title="预约结果" showBack onBack={() => navigate(-1)} />
      <div className={styles.container}>
        {success ? (
          <Result
            status='success'
            title={`预约成功：${bookingId}`}
            description={`请前往缴费中心支付 ¥${payAmount}，或在就诊记录中查看详情。`}
          />
        ) : (
          <Result
            status='warning'
            title='预约失败'
            description='很抱歉，当前号源不足或网络异常，请稍后重试。'
          />
        )}
        <div className={styles.actions}>
          <Button color='primary' onClick={() => navigate('/profile')}>就诊记录</Button>
          <Button onClick={() => navigate('/payment')} style={{ marginLeft: 8 }}>缴费中心</Button>
        </div>
      </div>
    </div>
  )
}

export default RegisterResult


